package com.hildeberto.home.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Hildeberto Mendonca
 */
public enum EntityManagerHelper {
    EM;

    EntityManagerFactory emf;
    EntityManager em;

    public EntityManager open() {
        if(emf == null || !emf.isOpen()) {
            emf = Persistence.createEntityManagerFactory("home-pu");
        }

        if(em == null || !em.isOpen()) {
            em = emf.createEntityManager();
        }

        return em;
    }

    public void beginTransaction() {
        em.getTransaction().begin();
    }

    public void commit() {
        if(em.getTransaction().isActive()) {
            em.getTransaction().commit();
        }
    }

    public void rollback() {
        if(em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }

    public void close() {
        if(em.isOpen()) {
            em.close();
            em = null;
        }

        if(emf.isOpen()) {
            emf.close();
            emf = null;
        }
    }
}